from rest_framework import serializers

from goods.models import SKU

'''前段传入的值　sku_id　count　selected'''
class UserCartSerializers(serializers.Serializer):
    sku_id=serializers.IntegerField(min_value=1)
    count=serializers.IntegerField(min_value=1)
    selected=serializers.BooleanField(default=True)

    def validate(self, attrs):
        sku_id=attrs['sku_id']
        count=attrs['count']
        # 校验有没有这个商品
        try:
            sku=SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('没有这个商品')
        # 校验库存
        if sku.stock <count:
            raise serializers.ValidationError('库存不够')
        return attrs


class CartSerializer(serializers.ModelSerializer):
    count = serializers.IntegerField()
    selected = serializers.BooleanField()

    class Meta:
        model =SKU
        '''fields '''
        fields = ('id', 'name', 'price', 'default_image_url','count','selected')



class UserPutSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1)
    count = serializers.IntegerField(min_value=1)
    selected = serializers.BooleanField(default=True)

    def validate_sku_id(self, value):
        try:
            sku=SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('没有这个商品')
        return value

class UserDeleteSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1)

    def validate_sku_id(self, value):
        try:
            sku=SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('没有这个商品')
        return value